package
{
	import com.xcopy.Common;
	import com.xcopy.Screen;
	import fl.controls.Button;
	import flash.display.MovieClip;
	import flash.display.Shape;
	import flash.display.SimpleButton;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Transform;
	import flash.text.AntiAliasType;
	import flash.text.Font;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;

	// 拉霸機的大廳（機台列表）
	public class Slot25Lobby extends Screen
	{
		public const SWITCH_LOBBY:String            = 'SWITCH_LOBBY';
		public const TYPE_GIRL:Number               = 0;
		public const TYPE_JUNGLE:Number             = 1;
		protected var _type:Number                  = 0; // 本機機種 0 拜金女 1 森林
		protected var _num:Number                   = -1; // 目前所選擇的機台號碼
		protected var _page:Number                  = 0; // 目前所在頁碼，從 0~29 頁共 30 頁，每頁 10 台共 300 台。 
		protected var _size:Number                  = 10; // 一頁有幾台機器
		protected var _datas:Array                  = []; // 機台的資料陣列
		protected var _machines:Vector.<Slot25Seat> = Vector.<Slot25Seat>([]); // 機台的影片陣列		
		protected var _pageMD5:Array                = []; // 每頁的 md5 快取
		// 設定連線彩金數值與播放動畫
		protected var _jackpot:DigitalBox           = new DigitalBox(this);
		private var _table:Slot25Table;
		private var oInfo:MovieClip;
		private var txtName:TextField;
		private var txtJackpot:TextField;
		private var txtLight:TextField;
		private var txtKeep:TextField;

		public function get table():Slot25Table
		{
			return _table;
		}

		public function get machine():Slot25Machine
		{
			return table.machine;
		}

		public function get main():NewBridge_25LineSlot
		{
			return table.main;
		}

		public function get debug():Slot25Debugger
		{
			return main.debug;
		}

		public function get client():FGS18Processer
		{
			return main.client;
		}

		public function get core():Slot25Core
		{
			return main.core;
		}

		public function set defaultType(n:Number):void
		{
			_type = n;
		}

		public function set type(n:Number):void
		{
			_type = n;
		}

		public function get type():Number
		{
			return _type;
		}

		public function set jackpot(n:Number):void
		{
			_jackpot.target = n;
		}

		public function get jackpot():Number
		{
			return _jackpot.number;
		}

		public function Slot25Lobby(r:* = null)
		{
			super(r);
			_table = r as Slot25Table;
			var i:Number = 0;
			for (i = 0; i < 30; i++)
			{
				_pageMD5[i] = 0;
			}
			for (i = 0; i < 300; i++)
			{
				_datas[i] = [];
				_datas[i]['V1'] = i; // 編號
				_datas[i]['V2'] = ''; // 帳號
				_datas[i]['V3'] = ''; // 暱稱
				_datas[i]['V4'] = 0; // md5 字串
				_datas[i]['V5'] = 0; // 保留時間
				_datas[i]['V6'] = 0; // Jackpot
				_datas[i]['V7'] = 0; // 星數
				_datas[i]['V8'] = i; // 娃娃
			}
		}

		public function askMachineStar(num:Number):Number
		{
			return _datas[num]['V7'];
		}

		override public function set clip(mc:MovieClip):void
		{
			super.clip = mc;
			var i:Number = 0;
			var seat:Slot25Seat;
			for (i = 0; i < 10; i++)
			{
				var _mc:MovieClip = clip.getChildByName('oSlot' + (i + 1)) as MovieClip;
				seat = new Slot25Seat(this);
				seat.clip = _mc;
				seat.CallbackClick = clickSeat;
				seat.CallbackOver = overSeat;
				seat.CallbackOut = outSeat;
				_machines.push(seat);
			}
			setClickEvent(clip.btnExit, exitGame);
			setClickEvent(clip.btnAuto, autoGame);
			setClickEvent(clip.btnNext, nextPage);
			setClickEvent(clip.btnPrev, prevPage);
			setClickEvent(clip.btnPage1, createCallBack(flipPage, 0));
			setClickEvent(clip.btnPage2, createCallBack(flipPage, 1));
			setClickEvent(clip.btnPage3, createCallBack(flipPage, 2));
			setClickEvent(clip.btnLobby0, createCallBack(switchLobby, 0));
			setClickEvent(clip.btnLobby1, createCallBack(switchLobby, 1));
			_jackpot.clip = clip.oJackpot;
			if (clip.oInfo)
			{
				oInfo = clip.oInfo;
				txtName = oInfo.txtName;
				txtJackpot = oInfo.txtJackpot;
				txtLight = oInfo.txtLight;
				txtKeep = oInfo.txtKeep;
				txtName.autoSize = TextFieldAutoSize.LEFT;
				txtJackpot.autoSize = TextFieldAutoSize.LEFT;
				txtLight.autoSize = TextFieldAutoSize.LEFT;
				txtKeep.autoSize = TextFieldAutoSize.LEFT;
				oInfo.visible = false;
			}
			disable();
		}

		// 點了坐位，看是否有保留決定送出指令
		public function clickSeat(num:Number):void
		{
			var machineNum:Number = num % 10;
			var seat:Slot25Seat   = _machines[machineNum];
			_num = num;
			switch (seat.state)
			{
				case Slot25Seat.STATE_NONE: // 無人使用，直接坐下
				{
					sendIntoSeat(_type, num, '');
					break;
				}
				case Slot25Seat.STATE_USE: // 有人使用，直接拒絕
				{
					this.table.alert.addAlert('本機台正在使用中，請挑選其他機台。');
					break;
				}
				case Slot25Seat.STATE_RESERVE: // 機台保留
				{
					if (seat.account == this.core.ID)
					{
						sendIntoSeat(_type, num, '');
					}
					else
					{
						this.table.alert.addLogin(sendLogin);
					}
					break;
				}
				default:
				{
					trace('機台狀態未列入 ' + seat.state);
				}
			}
		}

		// 點了坐位，看是否有保留決定送出指令
		public function overSeat(num:Number):void
		{
			oInfo.visible = true;
			oInfo.x = _machines[num % 10].clip.x;
			oInfo.y = _machines[num % 10].clip.y;
			var keeping:String = '';
			var value:Number   = 0;
			if (_datas[num]['V2'] == '')
			{
				oInfo.oScreen.gotoAndStop('Normal');
			}
			else
			{
				if (_datas[num]['V5'] == 0)
				{
					oInfo.oScreen.gotoAndStop('Face' + _datas[num]['V8']);
				}
				else
				{
					oInfo.oScreen.gotoAndStop('Reserve');
					value = int(_datas[num]['V5'] / 1000);
					keeping = int(value / 60) + ' : ' + ((value % 60) < 10 ? '0' : '') + (value % 60);
				}
			}
			var temp:String = _datas[num]['V3'];
			if (temp.length > 13)
			{
				temp = temp.substr(0, 12) + '..';
			}
			txtName.text = temp;
			txtJackpot.text = _datas[num]['V6'];
			txtLight.text = _datas[num]['V7'] + ' / 5';
			txtKeep.text = keeping;
		}

		public function outSeat(num:Number):void
		{
			oInfo.visible = false;
		}

		public function sendLogin(pass:String):void
		{
			sendIntoSeat(_type, _num, pass);
		}

		public function autoGame(e:MouseEvent):void
		{
			sendIntoSeat(_type, -1, '');
		}

		public function exitGame(e:MouseEvent):void
		{
			this.main.endGame();
		}

		public function nextPage(e:MouseEvent):void
		{
			if (page < 29)
			{
				page++;
			}
			else
			{
				page = 0;
			}
		}

		public function prevPage(e:MouseEvent):void
		{
			if (page > 0)
			{
				page--;
			}
			else
			{
				page = 29;
			}
		}

		public function flipPage(n:Number):void
		{
			page = n * 10;
		}

		public function switchLobby(n:Number):void
		{
			/** 廳別不變則 return */
			if (n == _type)
			{
				return;
			}
			table.music = '';
			main.tables[n].music = 'Lobby';
			sendIntoLobby(n);
		}

		public function clearTable():void
		{
			var i:Number = 0;
			for (i = 0; i < 10; i++)
			{
				_machines[i].reset(0);
			}
		}

		public function set page(num:Number):void
		{
			_page = num;
			sendListTable(_type, _page, _pageMD5[_page]);
			refreshPage(_page);
		}

		public function get page():Number
		{
			return _page;
		}

		public function requestPage(num:Number = -1):void
		{
			if (num == -1)
			{
				num = _page;
			}
			page = num;
		}

		// 將本頁清空並設為目前 datas 裡的資料，等待 server 回傳。
		public function refreshPage(num:Number):void
		{
			var i:Number    = 0;
			var user:Number = 0;
			if (num == -1)
			{
				num = _page;
			}
			for (i = 0; i < _size; i++)
			{
				user = _page * _size + i;
				_machines[i].num = _datas[user]['V1'];
				if (this.machine.serial == user && this.machine.state != Slot25Machine.STATE_NONE)
				{
					//trace('正在使用 ' + user + '有' + _datas[user]['V7']);
					this.machine.scrollTarget = _datas[user]['V7'];
				}
				// 看帳號來判斷有沒有人在玩，如果有則坐下，沒有則離開
				if (_datas[user]['V2'] == '')
				{
					//trace('leave');
					_machines[i].leave(_datas[user]['V7']);
				}
				else
				{
					//trace('sit');
					_machines[i].sit(_datas[user]['V2'], _datas[user]['V8'], _datas[user]['V5']);
				}
			}
			switchTab(Math.floor(_page / 10) + 1);
		}

		// 設定單頁資訊
		public function setPageInfo(s:String):void
		{
			// 由 S2C_setTableList 傳來資訊後，將之解析至該頁，並且若現在正在該頁，則佈置在畫面上
			var rows:Array        = s.split("\n");
			var row:String        = '';
			var rowNum:Number;
			var colNum:Number;
			var cols:Array        = [];
			var returnPage:Number = 0;
			var label:String      = '';
			var i:Number          = 0;
			//this.debug.print('setPageInfo：[' + s + ']');
			for (i = 0; i < _machines.length; i++)
			{
				_machines[i].alreadySet = true;
			}
			for each (row in rows)
			{
				row = row.replace("\r", '');
				label = row.charAt(0);
				switch (label)
				{
					case '[':
					{
						rowNum = Number(row.replace('[', '').replace(']', ''));
						returnPage = Math.floor(rowNum / 10);
						break;
					}
					case 'V':
					{
						cols = row.split(' = ');
						_datas[rowNum][cols[0]] = cols[1];
						break;
					}
				}
			}
			//trace('第 ' + returnPage + '頁資訊傳回，[' + rowNum + ']MD5 為' +
			_pageMD5[returnPage] = _datas[rowNum]['V4'];
			refreshPage(_page);
		}

		public function switchTab(n:Number):void
		{
			var i:Number = 0;
			var mc:MovieClip;
			var button:SimpleButton;
			for (i = 1; i <= 3; i++)
			{
				mc = clip.getChildByName('oPage' + i) as MovieClip;
				mc.visible = (n == i);
				button = clip.getChildByName('btnPage' + i) as SimpleButton;
				button.visible = !(n == i);
			}
		}

		// 送出換廳指令
		public function sendIntoLobby(type:Number):void
		{
			this.debug.print('>> C2S_ChooseGame：[' + type + ']');
			this.client.C2S_ChooseGame(type);
		}

		// 送出列表指令
		public function sendListTable(game:int, page:int, md5:int):void
		{
			//this.debug.print('>> C2S_getTableList：[' + game + ',' + page + ',' + md5 + ']');
			this.client.C2S_getTableList(game, page, md5);
		}

		// 送出入坐指令
		public function sendIntoSeat(game:Number, seat:Number, pass:String):void
		{
			this.debug.print('>> C2S_IntoTable：[' + game + ',' + seat + ',' + pass + ']');
			this.client.C2S_IntoTable(game, seat, pass);
		}
	}
}
